package com.example.demo.controller;

import com.example.demo.pojo.User;
import com.example.demo.pojo.Result;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.Md5Util;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Data
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")

    public Result<String> register(String username, String password) {
        if(username != null && username.length() >= 4 && username.length() <=16 && password != null && password.length() >=6 && password.length() <= 16){
            //查询用户
            User u = userService.findByUserName(username);
            if (u == null) {
                // 没有占用，那就注册
                userService.register(username, password);
                return Result.success();
            }
            else {
                return Result.error("用户名已被占用");
            }
        }
        else {
            return Result.error("参数不合法");
        }
    }

    @PostMapping("/login")
    public Result<String> login(String username, String password){
        if(username != null && username.length() >= 4 && username.length() <=16 && password != null && password.length() >=6 && password.length() <= 16){
            //根据用户名查询用户
            User loginUser = userService.findByUserName(username);
            //判断用户是否存在
            if (loginUser == null) {
                return Result.error("用户名错误");
            }
            //判断密码对不对
            if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){

                //登陆成功
                Map<String,Object> claims = new HashMap<>();
                claims.put("id",loginUser.getId());
                claims.put("username",loginUser.getUsername());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            }

            return Result.success("密码错误");


        }
        else {
            return Result.error("参数不合法");
        }
    }

}

